<template>
	<view class="base-page">
		<u-notify ref="uNotify"></u-notify> <!-- 通知横幅 -->
		<u-modal :show="showedit" title="是否确认添加信息" content="添加后需等待审核" :closeOnClickOverlay="true" showCancelButton
			@confirm="submitEdit()" @cancel="showedit = false" @close="showedit = false" :asyncClose="true"></u-modal>
		<!-- 修改确认模态框 -->
		<u-picker :show="showselect" ref="uPicker" :columns="houseList" closeOnClickOverlay @confirm="selectHouse()"
			@cancel="showselect = false" @close="showselect = false"></u-picker> <!-- 房屋选择器 -->
		<view class="info-list">
			<u-cell-group>
				<u-form :model="userInfo" :rules="rules" ref="uForm">
					<u-form-item prop="photo">
						<u-cell title="修改照片" v-if="userInfo.photostatus != 1">
							<u--image slot="value" :showLoading="true" :src="userInfo.photo" width="200rpx"
								height="200rpx" mode="aspectFill" @click="clickImage"></u--image>
						</u-cell>
						<!-- 正在审核时的照片 -->
						<u-cell title="修改照片" v-if="userInfo.photostatus == 1">
							<u--image slot="value" :showLoading="true" src="/static/review.png" width="200rpx"
								height="200rpx" mode="aspectFit" @click="clickImage"></u--image>
						</u-cell>
					</u-form-item>
					<u-form-item prop="car">
						<u-cell title="录入车辆">
							<u-input slot="value" placeholder="如: 京A123456" border="bottom" maxlength="10"
								v-model="userInfo.car"></u-input>
						</u-cell>
					</u-form-item>
					<u-form-item prop="houselocation">
						<u-cell title="录入房产" is-link @click="clickHouse()">
							<u-input slot="value" placeholder="点击选择房屋" border="none" maxlength="10"
								v-model="userInfo.houselocation" readonly></u-input>
						</u-cell>
					</u-form-item>
				</u-form>
			</u-cell-group>
		</view>
		<u-gap height="100rpx" bgColor="#ffffff"></u-gap>
		<view class="submit-btn">
			<u-button text="完成" type="primary" plain size="normal" @click="clickEdit()"></u-button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				//用户信息
				userInfo: {
					id: "",
					photo: "",
					car: "",
					//生成的数字房号
					housenumber: NaN,
					//显示的房屋位置
					houselocation: "",
					photostatus: 0,
				},
				//构造的四维数组
				houseList: [],
				//得到的房屋信息
				houseInfo: {
					D: 9, //栋
					C: 6, //单元
					F: 2, //层
					N: 8, //号
				},

				//信息修改发生
				isedit: false,

				//模态框控制
				showedit: false,
				//选择器控制
				showselect: false,

				//登录态与token
				responseResult: [],
				islogin: false,
				mytoken: '', //token

				//表单验证规则
				rules: {
					'car': {
						validator: (rule, value, callback) => {
							// 返回true表示校验通过，返回false表示不通过
							if (this.userInfo.car != "") {
								return uni.$u.test.carNo(value);
							} else {
								return true
							}
						},
						message: '车牌号格式错误',
						trigger: ['blur'],
					},
				},
			};
		},
		methods: {
			//从缓存获取用户信息
			setUser() {
				this.userInfo.id = uni.getStorageSync("Id")
				this.userInfo.photo = uni.getStorageSync("Photo")
				this.userInfo.photostatus = uni.getStorageSync("PhotoStatus")
			},
			//获取房屋信息
			getHouse() {
				uni.request({
					url: getApp().globalData.baseUrl + '/landlord/getHouseDCFN',
					method: 'GET',
					header: {
						'Authorization': 'Bearer ' + this.mytoken
					},
					success: (res) => {
						this.responseResult = res.data;
						if (this.responseResult.success == true) {
							this.houseInfo.D = this.responseResult.data.D //获取栋数
							this.houseInfo.C = this.responseResult.data.C //获取单元数
							this.houseInfo.F = this.responseResult.data.F //获取层数
							this.houseInfo.N = this.responseResult.data.N //获取房号数
						} else {
							this.$refs.uNotify.warning(this.responseResult.errorMsg)
						}
					},
					fail: (err) => {
						this.$refs.uNotify.error("请求错误: 获取房屋信息失败")
					}
				});
			},
			//构造房屋信息数组
			toHouseList(d, c, f, n) {
				function createArray(length, firstItem) {
					const arr = [firstItem];
					for (let i = 1; i < length + 1; i++) {
						arr.push(i);
					}
					return arr;
				}
				return [
					createArray(d, '栋'),
					createArray(c, '单元'),
					createArray(f, '层'),
					createArray(n, '房间号')
				];
			},
			//点击选择房屋
			clickHouse() {
				//构造房屋信息数组
				this.houseList = this.toHouseList(this.houseInfo.D, this.houseInfo.C, this.houseInfo.F, this.houseInfo.N)
				this.showselect = true
			},
			//选择房屋
			selectHouse(e) {
				//转换为纯数字房号
				this.userInfo.housenumber = Number(String(e.value[0]) + String(e.value[1]) + String(e.value[2]) + String(e
					.value[3]))
				//若正确选择，则转换为房屋位置
				if (this.userInfo.housenumber > 1) {
					this.userInfo.houselocation = String(e.value[0]) + "栋" + String(e.value[1]) + "层" + String(e.value[
						2]) + "单元" + String(e.value[3]) + "号"
					this.showselect = false
				} else {
					this.userInfo.houselocation = ""
					uni.$u.toast('请正确选择房屋')
				}
			},
			//点击头像
			clickImage() {
				if (this.userInfo.photostatus == 1) {
					this.$refs.uNotify.warning("照片审核中，请耐心等待")
				} else {
					//拍照或从相册选择照片
					uni.chooseMedia({
						count: 1,
						mediaType: 'image',
						sourceType: ['album', 'camera'],
						camera: 'back',
						success: (res) => {
							this.userInfo.photo = res.tempFiles[0].tempFilePath
						}
					})
				}
			},
			//点击提交信息按钮
			clickEdit() {
				//验证填写的信息是否有效
				this.$refs.uForm.validate().then(res => {
					//校验通过,弹出确认提示框
					this.showedit = true
				}).catch(errors => {
					uni.$u.toast('请正确填写信息')
				})
			},

			//确认提交
			submitEdit() {
				//先判断是否发生信息修改
				if (this.userInfo.car != "") {
					this.isedit = true
				}
				if (this.userInfo.housenumber > 1) {
					this.isedit = true
				}
				if (this.userInfo.photo != uni.getStorageSync("Photo") && this.userInfo.photostatus != 1) {
					this.isedit = true
				}
				//未发生信息更改，则关闭确认框并弹出提示
				if (this.isedit === false) {
					this.showedit = false
					this.$refs.uNotify.warning("请先添加信息")
				} else if (this.userInfo.photo != uni.getStorageSync("Photo") && this.userInfo.photostatus != 1) {
					//如果发生信息修改，且存在照片更改，则先上传照片，人脸识别通过后再提交后续信息
					uni.uploadFile({
						url: getApp().globalData.baseUrl + '/landlord/uploadPhoto',
						filePath: this.userInfo.photo,
						name: 'file',
						header: {
							'Authorization': 'Bearer ' + this.mytoken
						},
						formData: {
							id: this.userInfo.id,
						},
						success: (res) => {
							this.responseResult = res.data;
							this.responseResult = JSON.parse(this.responseResult) /* 转化为json对象 */
							if (this.responseResult.success === true) {
								//人脸识别成功，则关闭确认框后，继续提交后续两项信息
								this.showedit = false
								//继续提交后两项
								if (this.userInfo.car != "") {
									this.addCar()
								}
								if (this.userInfo.housenumber > 1) {
									this.addHouse()
								}
								//返回上一页并弹出成功提示
								uni.reLaunch({
									url: "/pages/user/user?sign=1&msg=提交信息成功,请等待审核"
								})
							} else {
								//人脸识别不成功，则关闭确认框后，弹出非人脸提示
								this.showedit = false
								uni.$u.toast('请上传人脸照片')
							}
						},
						fail: (err) => {
							this.$refs.uNotify.error("请求错误: 添加照片失败")
						}
					});
				} else {
					//如果发生信息修改，但不存在照片更改，则直接提交后续信息，并返回上一页
					if (this.userInfo.car != "") {
						this.addCar()
					}
					if (this.userInfo.housenumber > 1) {
						this.addHouse()
					}
					//返回上一页并弹出成功提示
					uni.reLaunch({
						url: "/pages/user/user?sign=1&msg=提交信息成功,请等待审核"
					})
				}


			},
			//添加车辆
			addCar() {
				uni.request({
					url: getApp().globalData.baseUrl + '/landlord/addCar',
					method: 'GET',
					header: {
						'Authorization': 'Bearer ' + this.mytoken
					},
					data: {
						number: this.userInfo.car,
					},
					success: (res) => {},
					fail: (err) => {
						this.$refs.uNotify.error("请求错误: 添加车辆信息失败")
					}
				});
			},
			//添加房产
			addHouse() {
				uni.request({
					url: getApp().globalData.baseUrl + '/landlord/addHouse',
					method: 'GET',
					header: {
						'Authorization': 'Bearer ' + this.mytoken
					},
					data: {
						number: this.userInfo.houselocation
					},
					success: (res) => {},
					fail: (err) => {
						this.$refs.uNotify.error("请求错误: 添加房产信息失败")
					}
				});
			},
		},
		onLoad() {
			let token = uni.getStorageSync("MyToken")
			if (token) {
				this.islogin = true
				this.mytoken = token
				this.getHouse() //获取房屋信息
				this.setUser() //从缓存获取用户信息
			} else {
				this.islogin = false
			}
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.uForm.setRules(this.rules)
		},
	}
</script>

<style lang="scss">
	.base-page {
		background-color: #ffffff;
		height: 100%;
		box-sizing: border-box;
	}

	.info-list {
		.info-list-image {
			height: 200rpx;
		}
	}

	.submit-btn {
		width: 650rpx;
		margin-left: 50rpx;
	}
</style>